<?php

	function fta_getAllFormMailerFormDescriptors(&$db){

		$cmsDocument = new CmsDocument($db);
		$cmsDocument->flush();
		$cmsDocument->setActiveDocuments();
		$cmsDocument->addDocumentType('docFormDesc');
		$cmsDocument->resetIterator();
		
		$formDescriptors = array();
		foreach ($cmsDocument->documentCodes as $mailFormId){
			array_push($formDescriptors, fta_getFormMailerFormDescriptor($mailFormId->documentcode, $db));
		}
		
		return $formDescriptors;
	}
	
	/**
	 * simple wrapper around the form mailer descriptor, that can be used for other stuff..
	 * Enter description here ...
	 * @param unknown_type $formId
	 * @param unknown_type $db
	 */	
	function fta_getFormDescriptor($formId, &$db){
		return fta_getFormMailerFormDescriptor($formId, &$db);
	}
	
	/**
	 * @desc pulls the required fields through JSON
	 *
	 * @param integer $formid
	 * @param CmsDatabaseConnection $db
	 * @return 
	 */	
	function fta_getFormMailerFormDescriptor($mailFormId, &$db){
			
			$formCmsDocument = new CmsDocument($db);

			$formCmsDocument->addDocumentType('docFormDesc');
			$formCmsDocument->addConstraint('documentcode',$mailFormId);
			$formCmsDocument->setActiveDocuments();
			$formCmsDocument->resetIterator();
			$forms = $formCmsDocument->getAllDocuments();
			
			if(is_array($forms) && count($forms)==1){
				$formDescription = $forms[0];
			}else {
				return null;
			}

					
			if (strlen($formDescription->content) > 0 )	{
				$recipients = explode(",",$formDescription->content);
			} else {
				$recipients = array();
			}
			$recipients = json_encode($recipients);
			
			
			if (strlen($formDescription->extra10) > 0 )	{
				$bccRecipients = explode(",",$formDescription->extra10);
			} else {
				$bccRecipients = array();
			}
			$bccRecipients = json_encode($bccRecipients);
			
					
					//		thankYouEmailSubject sendThankYouEmail thankYouEmailText		
			$json = '{"sender": "'. $formDescription->author .'", "formId":' .$formDescription->documentcode . ' ,"recipients": '. $recipients . ' ,"bccRecipients": '. $bccRecipients .  ', "subject" : "'.$formDescription->title .'", "fields" : ' . $formDescription->shortdescription . ', "isFormBuilderReady" : "' . $formDescription->authorbio . '", "formHeading" : '. json_encode($formDescription->authordepartment). ', "thankyouHeading":'. json_encode($formDescription->organisationalname) .
				', "requiresAuth" : ' . ( @$formDescription->extra1 == 1 ? "true" : "false") . ''  .
				', "passwordFile" : ' . ( @strlen($formDescription->extra3) > 0 ? json_encode($formDescription->extra3) : '""') . '' .
				', "authRealm" : ' . ( @strlen($formDescription->extra2) > 0  ? json_encode($formDescription->extra2) : '""') . '' .
				', "sendThankYouEmail" : ' . json_encode( ($formDescription->address) ? true : false ) . '' .				
				', "thankYouEmailSubject" : ' . ( @strlen($formDescription->phone) > 0  ? json_encode($formDescription->phone) : '""') . '' .
				', "thankYouEmailText" : ' . ( @strlen($formDescription->fax) > 0  ? json_encode($formDescription->fax) : '""') . '' .
			' }'; 	
			//exit($json);
			$formDescription =  json_decode($json);				

			return $formDescription;
	} 
		
	/**
	 * @desc saves form information in the db and sends email to the recipient
	 *
	 * @param integer $formid
	 * @param string $postData
	 * @param string $recipients
	 
	 * @param CmsDatabaseConnection $db
	 
	 * @return 
	 */
	
	function fta_formMailerSendForm($formDescription, $postData, $recipients, $authInfo, &$invalidFields,&$db, &$rawPostData=null){
		
	
		// myPrintR($formDescription);
		// $formDescription = getMailFormDescriptor($formid,$db);
		
		if ($formDescription){
			$extractedFormData = array();
			
			if (is_null($invalidFields))
				$invalidFields = array();
				

			// validate the form..
			//$invalidFields = array();
			$extractedFormData = fta_formMailerValidateFormData($formDescription, $postData,$invalidFields);
			
			if (is_array($formDescription->recipients) && count($formDescription->recipients)>0  && is_array($recipients)&& count($recipients)>0 ) {
				$recipients = array_merge($formDescription->recipients, $recipients);
			} else if (is_array($formDescription->recipients) && count($formDescription->recipients)>0 ) {
				$recipients = $formDescription->recipients;
			} else if(is_array($recipients) && count($recipients)>0) {				
				$recipients = $recipients;
			} else {				
				$recipients = array(CMS_EMAIL_FROM);
			}
			
			if (is_array($formDescription->bccRecipients) && count($formDescription->bccRecipients)>0) {
				$bccRecipients = $formDescription->bccRecipients;
			} else {
				$bccRecipients = array();
			}
							
			//get this far .. we check to see if we have invalid fields or not..
			
			//myPrintR($extractedFormData);
			
		if(count($invalidFields) == 0 ){

			
			//if we have no errors here.. we need to go and upload the missing files into the file store..
			//this will simply be a bitbucket.. named after the form and can live anywhere in the cms files module..
			//if it does not exist, we give up..
			
			//1. get the parent folder..
			// ************************************************************
			// YOU NEED TO CREATE THIS FOLDER!
			// ************************************************************
			$cmsDocument = new CmsDocument($db);
			$cmsDocument->flush();
			$cmsDocument->addDocumentType("docFileMod");
			$cmsDocument->addConstraint("title", $formDescription->subject . " submitted files");
			$cmsDocument->resetIterator();
			
           
			if($cmsDocument->totalDocuments() == 1) {
                
				$folder = $cmsDocument->nextDocument();
			
				foreach($formDescription->fields as $field) {
					if ('file' != @$field->type) continue;
                    
                                   
					if (!is_array($extractedFormData[$field->id])) continue;
                    
                   					
					$fileDataToSave = array();
					
					$fileDataToSave['documenttypecode'] = 'docFileMod';
					$fileDataToSave['title'] = $formDescription->subject ." Submitted File - " . $field->id;
					$fileDataToSave['categorycode'] = $folder->documentcode;
					//$fileDataToSave['categorycode'] = $folder->documentcode;
					//$fileData
					
					$_FILES['content'] = $extractedFormData[$field->id];
					$_FILES['isactive'] = 1;//$extractedFormData[$field->id];
					
					//$fileDataToSave['author'] = 0;
					
					$ut = $authInfo->usertype;
					$authInfo->usertype = 0;
					$cmsWriter = new CmsWriter(220, null, $fileDataToSave, $authInfo, $db);				
					$message = $cmsWriter->processFormData();					
					unset($_FILES['content']);					
					$authInfo->usertype = $ut;
				

					// now update the field in the data so that we can embed a link...
					$extractedFormData[$field->id] = "<a href='" . CMS_HTTP_HOST . "/html/blob.php?documentCode=" . $cmsWriter->documentCode . "&elementId=11362'> Download " . $field->label . " attachment</a>";
					$extractedFormData[$field->id . "_id"] = $cmsWriter->documentCode;		
				}
			}
			
			//$from = "no-reply@gravitate.co.nz";//this needs to be pulled from the config or the form desc
			$from = $formDescription->sender;
			
	ob_start();//dont want the leading white space here
?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
	<head>
		<title><?= $formDescription->subject ?> Form Submission</title>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<style>
			.out { display:block; border:1px solid #ddd; position:relative; margin:0; width:  600px;}		
		</style>		
	</head>
	<body>
		<div class="mainFormContainer">
			<div class="out">
				<div class="in ltin tpin">
					<font face="Helvetica,Arial" weight="500">

						<table width="600" cellpadding="1" cellspacing="0">
<?	

for($s=0; $s<count($formDescription->fields); $s++){
	if(@$formDescription->fields[$s]->table == ""){

	$fieldValue = $extractedFormData[$formDescription->fields[$s]->id];
?>		
							<tr>
								<td  width="200" align="left" valign="top" ><font size="2" face="arial" color="#000000"><b><?= fta_outputClean($formDescription->fields[$s]->label) . ((@$formDescription->fields[$s]->sublabel) ? ": " .(fta_outputClean($formDescription->fields[$s]->sublabel)) : "" )?>:</b></font></td>
								<td class="field" align="left" valign="top">&nbsp;<font face="arial" size="2"><b>
								<? /* 2010-10-01 - JRM
									* Don't strip the A tag if it is a file
									*/ ?>
								<?= ($formDescription->fields[$s]->type === 'file') ? $fieldValue : fta_outputClean($fieldValue); ?>
								</b></font></td> 
							</tr>
<?
	
	} 
}	
?>
</table>



<?
$fieldsForTable = array();
for($v=0; $v<count($formDescription->fields); $v++){
	if(@$formDescription->fields[$v]->table != ""){
		array_push($fieldsForTable, $formDescription->fields[$v]);
	}
}

 	

if(is_array($fieldsForTable) && count($fieldsForTable) > 0){
	$columnLabels = array();
	for($o=0; $o<count($fieldsForTable); $o++){ 
			if($fieldsForTable[$o]->row == 1){
				array_push($columnLabels, $fieldsForTable[$o]->label);
			}
	}
	
?>
<table width="600" cellpadding="2" cellspacing="0" >
	
	<tr bgcolor="#E5E5E5">
<?
		$countLabelRow = 1;
		foreach($columnLabels as $fieldLabel){
			$labelStyle = "background:#d9d9d9;padding: 8px;border-right:1px solid #000;border-top:1px solid #000;border-bottom:1px solid #000;color:#000;";
			if($countLabelRow == count($columnLabels)) {
				$labelStyle = "background:#d9d9d9;padding: 8px;border-top:1px solid #000;border-top:1px solid #000;border-bottom:1px solid #000;color:#000;";
			}
?>
			<td valign="top" style="<?= $labelStyle; ?>"><font face="arial" size="2"><b><?= fta_outputClean($fieldLabel) ?></b></font></td>
<?			$countLabelRow++;
		}
?>	
	</tr>

<?	
	$countRow = 1;
	for($row=0, $w=0; $w<count($fieldsForTable);){
				
?>		
		<tr>					
<?
	 	for($u=0; $u<count($columnLabels); $u++){
	 		
	 		$bgCol = "";
			if($countRow%2 == 0) {
				$bgCol = "#e3e3e3";
			}
			
			
			if($u+1 == count($columnLabels)) {
				$tdStyle ="";
			} else {
				$tdStyle = "border-right:1px solid #000;";
			}
			
				 		
	 		if($fieldsForTable[$w]){
?>
				
				<td valign="top" style="<?= $tdStyle; ?>;" bgcolor="<?= $bgCol; ?>" <? if(@$fieldsForTable[$w]->width != ""){ ?> width="<?= fta_outputClean($fieldsForTable[$w]->width); ?>" <?}?>><? if($extractedFormData[$fieldsForTable[$w]->id] != ""){ echo "<font face=\"arial\" size=\"2\">" . fta_outputClean($extractedFormData[$fieldsForTable[$w]->id]) . "</font>"; } else { echo "&nbsp;"; } ?></td>
<?
	 		}
	 		$w++;
	 	}
?>
		</tr>			
<?
		$row++;
		$countRow++;
	}
?>		
</table>
<?
}
?>
						
					</font>
				</div>
			</div>
		</div>
	</body>
</html>
<?
	$formData = ob_get_clean();
					$dataToSave = array();
					$dataToSave['documenttypecode'] = 'docSubmtForm';
					$dataToSave['shortdescription'] = implode(", ", $recipients);
					$dataToSave['extra1'] = implode(", ", $bccRecipients);
					$dataToSave['content']	= $from;
					$dataToSave['author'] = $_SERVER['REMOTE_ADDR'];

					$dataToSave['title'] = $formDescription->subject ." Form Submission";//$formDescription->formId;
					$dataToSave['authordepartment'] = $formData;								

					
					$dataToSave['organisationalname'] = json_encode($extractedFormData);
					
					$ut = $authInfo->usertype;
					$authInfo->usertype =0;
					$cmsWriter = new CmsWriter(322, null, $dataToSave, $authInfo, $db);
					$message = $cmsWriter->processFormData();
					$authInfo->usertype =$ut;
					
					if (!is_null($rawPostData)){
						$rawPostData = $dataToSave['organisationalname'];
					}					
						  
						  $headers = array();
						  $headers['From']    = $from;
						  $headers['Return-Path']    = $from;
						  $headers['Reply-To'] = $from;
						  
						  $headers['To']      = "<" . implode(">,<", $recipients) . ">";
						  $headers['Subject'] = $formDescription->subject ." Form Submission";
		
						  $headers['Content-Type'] = "text/html; charset=utf-8";
						  $headers['Content-Transfer-Encoding'] = "8bit";
						  
						  $headers['Date'] = date("r");
						  						
						  $mail_object =& Mail::factory('smtp',($params= array('host'=> 'localhost')));
						  
						 if(is_array($bccRecipients) && count($bccRecipients) > 0){
						 	$recipients = array_merge($recipients,$bccRecipients);
						 	$res = $mail_object->send($recipients, $headers, $formData);	
						 } else {
						 	$res = $mail_object->send($recipients, $headers, $formData);
						 }
						  
						  
						  if (is_bool($res)) {
						  	return $res;
						  } else {
						  	false;
						  }
				
			} else 
				return false; 
		}	

		return false;
	}

	
	function fta_validateFormData($formDescription, &$postData, &$invalidFields){
		return 	fta_formMailerValidateFormData($formDescription, $postData, $invalidFields);
	}
	
	function fta_formMailerValidateFormData($formDescription, &$postData, &$invalidFields ) {
		//$invalidFields = array();
        
		$extractedFormData = array();
		foreach ($formDescription->fields as $field) {
			if (!@$field->type)
				$field->type = "string";
				
				
			if (@$field->fieldType ==  'date'){
				//we need to combine all fo the posted date fields into one date field..
				$postData[$field->id ] = @$postData[$field->id . 'Day'] . "-" . @$postData[$field->id . 'Month'] . "-" .  @$postData[$field->id . 'Year'];				
				
				if ($postData[$field->id ] == "--")
					unset ($postData[ $field->id ]);
					
			}
						
								
			$extractFunction = "extract" . ucfirst($field->type) . "WithKeyFromArray";
			$extractedFormData[ $field->id ] = $extractFunction($field->id, $postData, null);

			
			
			// here .. we want to skip this if we are checking a file.. cannot validate a file.. really..
			// so we set it to what ever was extracted.. we get nothing if its not an uploaded file.
			if ('file' == @$field->type) {	
                //$extractedFormData[ $field->id ] = $ex->{ $extractMethod }("form_".$formDescription->formId, $field->id, null);
               	$postData[ $field->id ] = $extractedFormData[ $field->id ];
			}
			
			
			if ('captcha' == @$field->type) {
				//here we need to take the cookie value and put it into the request..
				$extractedFormData[ $field->id ] = md5($extractedFormData[ $field->id ]);
				$postData[$field->id] = extractStringWithKeyFromArray('vihash',$_COOKIE);
			}
			
			// first check validity.. if we have something in the request.. and
			// we compare it to what is extracted... they should match..
			$compareValue = extractValueWithKeyFromArray($field->id,$postData,null);
			if (!is_null($compareValue)  ){
				// echo $field->id . ": '". $compareValue . "' - '" . $extractedFormData[ $field->id ] . "'<br/>";
				if (($compareValue) != $extractedFormData[ $field->id ]){
					$invalidFields[ $field->id ] = "contains an invalid value";
					continue;//skip the rest of this.. 
				}
			}
			
			
			//first we check for missing/required fields..
			if (@$field->isRequired){
				if (is_null($extractedFormData[ $field->id ]) || $compareValue === 'Please Select') {
					$invalidFields[ $field->id ] = "is a required field";
                }
			}	
		}	
		return $extractedFormData;
	}
	
	function fta_formMailerSendThankYouEmail($recipients, &$formDescription){

		if (!$formDescription->sendThankYouEmail)
			return false;
			
		$headers = array();
		$headers['From']    = $formDescription->sender;
		$headers['Return-Path']    = $formDescription->sender;
		$headers['Reply-To'] = $formDescription->sender;
						  
		$headers['To']      = "<" . implode(">,<", $recipients) . ">";
		$headers['Subject'] = $formDescription->thankYouEmailSubject;
		
		$headers['Content-Type'] = "text/html; charset=utf-8";
		$headers['Content-Transfer-Encoding'] = "8bit";
						  						
		$formData = "";
		ob_start();
?>
<html>
<head>
	<title><?= $formDescription->thankYouEmailSubject ?></title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<font face="Arial,Helvetica">
<?= $formDescription->thankYouEmailText ?>
</font>
</body>
</html>		
<?		
		$formData = ob_get_clean();
		
		$mail_object =& Mail::factory('smtp',($params= array('host'=> 'localhost')));
		
		$res = $mail_object->send($recipients, $headers, $formData);	
						  
						  
		if (is_bool($res)) {
			return $res;
		} else {
		 	false;
		}
						  
	
	}
		
	
	/**
	 * This is for getting the id/checked status of a radio group
	 */	
	function fta_getFormMailerInputIdAndValue($id, &$source, &$formDescription) {
?>
id="<?= $id ?>" name="<?= $id ?>" value="<?= addslashes(fta_outputClean(extractValueWithKeyFromArray($id,$source,null))); ?>"
<?
	}
	
	function fta_getFormInputIdAndValue($id, $source, &$formDescription){
		return fta_getFormMailerInputIdAndValue($id,$source,$formDescription);
	}
	
	
	/**
	 * This is for getting the id/checked status of a radio group
	 */		
	function fta_getFormMailerTextAreaValue($id, &$source, &$formDescription){
		echo extractValueWithKeyFromArray($id,$source,null);
	}
	
	
	/**
	 * This is for getting the id/checked status of a radio group
	 */	
	function fta_getFormMailerRadioGroupIdValueAndCheckedStatus($id, $selectedValue, &$source, &$formDescription){
		$checked = ($selectedValue  == extractValueWithKeyFromArray($id,$source,null));
		
?>
id="<?= $id . "_". $selectedValue ?>" name="<?= $id ?>" value="<?= $selectedValue ?>" <?= ($checked) ? 'checked="checked"' :"" ?>
<?
	}
	
	/**
	 * This is for getting the id/checked status of a single checkbox
	 */
	function fta_getFormMailerCheckBoxIdValueAndCheckedStatus($id, $selectedValue, &$source, &$formDescription){
		$checked = ($selectedValue  == extractValueWithKeyFromArray($id,$source,null))
		
?>
id="<?= $id . "_". $selectedValue ?>" name="<?= $id ?>" value="<?= $selectedValue ?>" <?= ($checked) ? 'checked="checked"' :"" ?>
<?
	}
	
	function fta_getFormCheckBoxIdValueAndCheckedStatus($id, $selectedValue, $source, &$formDescription){
		return fta_getFormMailerCheckBoxIdValueAndCheckedStatus($id, $selectedValue, $source, $formDescription);
	}
	//add check box group here when required.....
	
	
	/**
	 * this is for doing form mailers.. as such we dont care about the value field, only
	 * what is in the form drop down..
	 */
	function fta_getFormMailerDropDownOptions($id, $selections, $source, &$formDescription){
		foreach ($selections as $key=>$select){
			
			if($key !="" && !is_numeric($key)){
				$checked = ($key  == extractValueWithKeyFromArray($id,$source,null));
			} else {
				$checked = ($select  == extractValueWithKeyFromArray($id,$source,null));
			}
			
//puts $key as value for <option> - "value" has to be non-numeric	
?>
<option <?= ($checked) ? 'selected="selected"' :"" ?> <?if($key !="" && !is_numeric($key)){ echo "value=\"". $key ."\""; } else { echo "value=\"". $select ."\""; } ?> ><?= $select ?></option>
<?		}
	}
	
	
	function fta_getFormDropDownOptions($id, $selections, $source, &$formDescription){
		return fta_getFormMailerDropDownOptions($id, $selections, $source, $formDescription);
	}
	
	
	
	function fta_getValidationMessageForField($id, &$invalidFields, &$formDescription){
		 fta_getFormMailerValidationMessageForField($id, $invalidFields, $formDescription);
	}
	
	
	function fta_getFormMailerValidationMessageForField($id, &$invalidFields, &$formDescription) {
	
		if (is_array($invalidFields) && key_exists($id,$invalidFields)){

			//sigh.. linear search through an array..
			$label = $id;
			foreach ($formDescription->fields as $key => $field){
				if ($field->id == $id){
					$label = $field->label;
					break;
				}
			}
		
?>
<div class="formValidationError"><?= $label ?> <?= $invalidFields[ $id ]?>.</div>		
<?		
		}
	}
	
	
	
	/**
	 * @desc prints a mailout form
	 *
	 * @param integer $formid
	 * @param string $postData
	 *  
	 * @param CmsDatabaseConnection $db
	 
	 * @return 
	 */
	
	function fta_getFormMailerPrintForm($formDescription, $postData, &$invalidFields,&$db){
	
		
		if ($formDescription){
			
			$extractedFormData = array();
			
			if (is_null($invalidFields))
				$invalidFields = array();
				
			//perform validation on fields.
			$formGroups = array();
			$currentGroupLabel = "";
			foreach ($formDescription->fields as $field) {
				
				$currentGroupLabel = @($field->groupLabel && $currentGroupLabel !=  $field->groupLabel)? $field->groupLabel : $currentGroupLabel;


				if (!@$field->type)
					$field->type = "string";
					
				if (@$field->fieldType ==  'date'){
					//we need to combine all fo the posted date fields into one date field..
					$postData[$field->id ] = @$postData[$field->id . 'Day'] . "-" . @$postData[$field->id . 'Month'] . "-" .  @$postData[$field->id . 'Year'];				
					
					if ($postData[$field->id ] == "--")
						unset ($postData[ $field->id ]);
						
				}
				
				$extractFunction = "extract" . ucfirst($field->type) . "WithKeyFromArray";
				if (!key_exists($currentGroupLabel,$formGroups)){
					$formGroups[$currentGroupLabel] = array();
				}
				
				
				
				$extractedFormData[ $field->id ] = $extractFunction($field->id, $postData, null);
	
				// first check validity.. if we have something in the request.. and
				// we compare it to what is extracted... they should match..
				$compareValue = extractValueWithKeyFromArray($field->id,$postData,null);
				if (!is_null($compareValue)  ){
					//echo $field->id . ": '". $compareValue . "' - '" . $extractedFormData[ $field->id ] . "'<br/>";
					if (($compareValue) != $extractedFormData[ $field->id ]){
					//	$invalidFields[ $field->id ] = "contains an invalid value";// we remove this here as we dont want to check when we print,
					// we take the passed in invalid data..
						continue;//skip the rest of this.. 
					}
				}
				
				//first we check for missing/required fields..
				if (@$field->isRequired){
					if (is_null($extractedFormData[ $field->id ]) || $compareValue == 'Please Select') {
					//	$invalidFields[ $field->id ] = "is a required field";// we remove this here as we dont want to check when we print,
					// we take the passed in invalid data..
					}
				}
				//
				
	
				if (key_exists('table',$field) && strlen($field->table)>0) {
					
					
					if (!is_array(@$formGroups[$currentGroupLabel][$field->table])) {
						$formGroups[$currentGroupLabel][$field->table] = array();
						$formGroups[$currentGroupLabel][$field->table]['table'] = true;						
					}
					array_push($formGroups[$currentGroupLabel][$field->table], $field);

				} else {
					$formGroups[$currentGroupLabel][$field->id] = $field;
				}
			}

			
	ob_start();//dont want the leading white space here
	
	/*//<div class="formH2"><h2 class="sifr"><?= "Form Section Title" ?></h2></div>*/
	foreach ($formGroups as $formGroupTitle => $formGroup){
		
		if (strlen($formGroupTitle) > 0 ){
?>
<div class="formH2"><h2 class="sifr"><?= $formGroupTitle ?></h2></div>
<?
		}
?>
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="formBuilder">
<?		
		$fg = $formGroup;
		//foreach ($formGroup as $field){
		while ($field = array_shift($fg)) {
?>
<tr>
<?
			// we now need to figure out if the field is a table.. a cluster .. or a normal row..
			// and we need to decide how the clusterin will work
			$rowBaseClass = "formCellL";

			if (count($fg) == 0){
				$rowBaseClass = "formCellB";
			}
			
			if ( is_array($field)){
			//	echo "have table or group of elements";
?>
<td colspan="2">
<?


	//First are we a table??
	if ($field['table']){
		
		$fieldsForTable = $field;
		unset($fieldsForTable['table']);
		
		
////		
if(is_array($fieldsForTable) && count($fieldsForTable) > 0){
	
	//work out the column labels.
	$columnLabels = array();
	for($o=0; $o<count($fieldsForTable); $o++){ 
		if($fieldsForTable[$o]->row == 1){
			array_push($columnLabels, $fieldsForTable[$o]->label);
		}
	}
	//$tdWidth = 100/count($columnLabels);
	
?>
<table cellpadding="0" cellspacing="0" class="formTable">	
	<tr >
<?
		$countLabelRow = 1;
		foreach($columnLabels as $fieldLabel){
			
			$labelClass = ($countLabelRow == count($columnLabels)) ? "formTableHeading" : "formTableHeadingLast";
?>
			<th class="<?= $labelClass ?>" ><?= fta_outputClean($fieldLabel) ?></th>
<?			$countLabelRow++;
		}
?>	
	</tr>

<?	
	$countRow = 1;
	for($row=0, $w=0; $w < count($fieldsForTable);){
		$rowClass = ($countRow%2 == 0) ? "odd" : "even";			
?>		
		<tr class="<?= $rowClass ?>" >					
<?
	 	for($u=0; $u<count($columnLabels); $u++){				 		
	 		if($fieldsForTable[$w]){
				$cellClass = ($u+1 == count($columnLabels)) ? "formTableCell" : "formTableCellLast";
		 		$cellWidth = (@$fieldsForTable[$w]->width != "") ? 'width="'. fta_outputClean($fieldsForTable[$w]->width) . '"' : "";
?>
				
				<td class="<?= $cellClass ?>" <?= $cellWidth ?> >
<?
					//print the element here... 
					fta_getFormMailerFormField($fieldsForTable[$w]->id, $postData ,$formDescription, $db);
					fta_getValidationMessageForField($fieldsForTable[$w]->id,$invalidFields,$formDescription);
?>
				</td>
<?
	 		}
	 		$w++;
	 	}
?>
		</tr>			
<?
		$row++;
		$countRow++;
	}
?>		
</table>
<?
}				
////		
		
	} else if ($field['group']){
	} else {
	}
?>
</td>
<?			
			} else {
?>
<td width="24%" align="right" class="<?= $rowBaseClass ?>"><?= (@$field->isRequired) ? "<span class=\"red\" >" : "" ?><?= $field->label ?>:<?= (@$field->isRequired) ? "</span >" : ""?></td>
<td width="76%" class="formCellR">
<?

	if (@strlen($field->sublabel) > 0) {
		echo "<p class=\"sublabel\">" . $field->sublabel . "</p>";
	}
	
	fta_getFormMailerFormField($field->id, $postData ,$formDescription,$db);
	fta_getValidationMessageForField($field->id,$invalidFields,$formDescription);
?>
</td>
<?				
			}
?>
</tr>
<?
		}
?>
</table>
<?		
			}
			return ob_get_clean();
		}	
		return "";
	}
	

	function fta_getFormMailerFieldWithIdFromFormDescription($id, $formDescriptor){
		foreach ($formDescriptor->fields as $key => $field){
			if ($field->id == $id){
				return $field;
			}
		}
	}

	
	function fta_getFormMailerOptionsForField($fieldDescriptor,&$db) {
		if (@$fieldDescriptor->optionsQuery){			
			$options = $db->getAllAsArray($fieldDescriptor->optionsQuery,($a = array()));
			$returnOptions = array();
			foreach ($options as $o) {
				array_push($returnOptions, $o[0]);
			}
			return $returnOptions;
		} else if (is_array($fieldDescriptor->options)){
			return $fieldDescriptor->options;
		} else {
			return array();
		}
	}
	
	function fta_getFormMailerFormField($id,&$source, &$formDescriptor,&$db){
		
		$field = fta_getFormMailerFieldWithIdFromFormDescription($id, $formDescriptor);
		if (is_null($field))
			return;
					
			
		//pull out any options that may be present here..
		switch (@$field->fieldType){
			
			//assumes a group of radio buttons
			//checkbox group
			case 'file':
				?><input <?= fta_getFormMailerInputIdAndValue($id, $source,$formDescription); ?> type="file">	<?
				break;
			case 'check':
				$groupType = "checkbox";						
			case 'radio':
				if (!@$groupType)
					$groupType="radio";
			
			$options = fta_getFormMailerOptionsForField($field,$db);
			
			foreach ($options as $option){		
?>				
<?= ($field->fieldType == 'radio') ? $option : ""?> <input <?= fta_getFormMailerRadioGroupIdValueAndCheckedStatus($id, $option, $source, $formDescriptor); ?> type="<?= $groupType ?>"/><?= ($field->fieldType == 'radio') ? "" : $option ?><?= (@$field->layout == "vertical") ? "<br/>" : "" ?>
<?			
			}
			break;

			//check box with only yes/no as values
			case 'yesno':
				?>

<input <?= fta_getFormMailerCheckBoxIdValueAndCheckedStatus($id, 'Yes', $source, $formDescriptor); ?> type="checkbox"/>
<?				
			break;
			
			// yes no .. but in a drop down
			case 'yesnodropdown':
?>
<select id="<?= $id ?>" name="<?= $id ?>" >	
<?
	if (!@$field->isRequired){
?>
<option>Please Select</option>		
<?
	}
?>
<? fta_getFormMailerDropDownOptions($id,( $a = array('Yes','No')),$source,$formDescription); ?>
</select>
<?				
			break;


			
			//drop down menu
			case 'dropdown':
				
				//check for a query..
				$options = fta_getFormMailerOptionsForField($field,$db);
?>
<select id="<?= $id ?>" name="<?= $id ?>" >	
<option>Please Select</option>		
<? fta_getFormMailerDropDownOptions($id,$options,$source,$formDescription); ?>
</select>
<?
			break;
			
			//prints a date picker combination
			case 'date':
?>
                                    <select name="<?= $id ?>Day">
                                          <option selected>-</option>
<?

	$days =array();
	for ($i=1; $i<=31; $i++){
		if($i > 0 && $i < 10){
			$j = "0" . $i;
		}else{
			$j = $i;
		}
		array_push($days,$j);
	}
		
	fta_getFormMailerDropDownOptions($id . 'Day',$days,$_REQUEST,$formDescription);?>     
                                        </select>
                                        
                                        <select name="<?= $id ?>Month">
                                          <option selected>-</option>
<? 
	$months =array();
	for ($i=1; $i<=12; $i++){
		if($i > 0 && $i < 10){
			$j = "0" . $i;
		}else{
			$j = $i;
		}
		array_push($months,$j);
	}	
	fta_getFormMailerDropDownOptions($id . 'Month',$months,$source,$formDescription);?>
            
                                        </select> <select name="<?= $id ?>Year">
                                          <option selected>-</option>
<? 
	$years =array();
	for ($i=2004; $i<=2015; $i++)
		array_push($years,$i);
	
	fta_getFormMailerDropDownOptions($id . 'Year',$years,$source,$formDescription);?>
                                   </select>

<?				
			break;
			
			case 'text':
?>				
<textarea name="<?= $id ?>" id="<?= $id ?>" class="textarea"><?= fta_getFormMailerTextAreaValue($id, $source, $formDescription); ?></textarea>				
<?
			break;
			
			default:
?>
<input <?= (@$field->width && strpos($field->width,'%') === false) ? "style=\"width: ". ($field->width - 10) ."px;\"" : "" ?> class="textfield" <?= fta_getFormMailerInputIdAndValue($id, $source,$formDescription); ?> />
<?				
			break;
		}
	}
	
	
	
	class FTAForm  implements Iterator {
		
		protected $formDescriptor;
		protected $fieldIndex;
		protected $formDescriptorId;
		protected $invalidData;
		
		//need a list of a) required fields
		// and b) a list of fields that need different validation rules..
		function __construct($formDescriptorId){
			global $db;
			
			$this->formDescriptorId = $formDescriptorId;
			$this->formDescriptor = fta_getFormDescriptor( $this->formDescriptorId , $db);
			//loop over the form descriptor and add the fields to the object;
			if (is_null($this->formDescriptor)){
				throw new FTAException("Form descriptor not found");
			}
			
			foreach($this->formDescriptor->fields as $element){
				$this->{ $element->id } = null;
			}
			
			$this->iteratorIndex = 0;
		}
		
		//is data valid?? call the fta validation
		function isValid(){
			$this->invalidData = array();
			

			$data = array();
			foreach ($this as $field => $value){
				$data[$field] = $value;
			}
			$returnData = fta_validateFormData($this->formDescriptor, $data , $this->invalidData);
			
			return (0 === count($this->invalidData)); 
		}
		
		function getInvalidData(){
			return $this->invalidData;
		}

		function setInvalidData($invalidData){
			$this->invalidData = $invalidData;
		}
				
		function getFormDescriptor(){
			return $this->formDescriptor;
		}
		
		function takeValuesFrom($i){		
	//	function takeValuesFrom(Iterator $i){
	// so arrays in php are not iterators.. grumble.. 
			foreach ($i as $key => $value){
				if (property_exists($this,  $key )){
					$this->{ $key } = $value;
				}
			}			
		}
		
		
		
		//iterator implementations	.. don't alter unless there is a reall serious need to.. 
		function current(){
			return $this->{ $this->formDescriptor->fields[$this->iteratorIndex]->id };
		}
		
		function next() {
			//check that the field exists..
			if (isset($this->formDescriptor->fields[++$this->iteratorIndex]) && isset($this->{ $this->formDescriptor->fields[$this->iteratorIndex]->id })){
				return $this->{ $this->formDescriptor->fields[$this->iteratorIndex]->id };
			} else {
				return false;
			}
		}
		
		function key(){
			return $this->formDescriptor->fields[$this->iteratorIndex]->id;
		}
		
		function rewind(){
			$this->iteratorIndex = 0;
		}
		
		function valid() {
			return isset($this->formDescriptor->fields[$this->iteratorIndex]);
		}
		
		
		//odd overrides here?? for isset etc??
	}
		
	
	
